package com.young.common.util;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.security.NoSuchAlgorithmException;

/**
 * HS256加密工具
 * @author imrookie
 * @date 2018/9/16
 */
public class HS256Util {

    public static String KEY_ALGORITHM = "HmacSHA256";//hs256算法

    /**
     * 加密
     * @param message 明文
     * @param key 密钥
     * @return 密文
     */
    public static String encrypt(String message, String key) throws Exception{
        String hash = null;
        try {
            Mac mac = Mac.getInstance(KEY_ALGORITHM);
            SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), KEY_ALGORITHM);
            mac.init(secretKeySpec);

            byte[] bytes = mac.doFinal(message.getBytes());
            hash = byteArrayToHexString(bytes);
        } catch (NoSuchAlgorithmException e) {
            throw new Exception(e);
        }
        return hash;
    }

    private static String byteArrayToHexString(byte[] bytes){
        StringBuilder sb = new StringBuilder("");
        String stmp;
        if (bytes != null){
            for (int n = 0; n < bytes.length; n++) {
                stmp = Integer.toHexString(bytes[n] & 0XFF);
                if (stmp.length() == 1){
                    sb.append('0');
                }
                sb.append(stmp);
            }
        }
        return sb.toString();
    }
}
